package com.ir.slassm.domain;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ir.slassm.dao.NameValueDAO;
import com.ir.slassm.vo.NameValueVO;

public class PropertyManager {
	Log logger = LogFactory.getLog(PropertyManager.class);
	private NameValueDAO nameValueDao;
	
	public static final String PROPERTY_ATTRIBUTE_GROUP = "group";
	public static final String PROPERTY_ATTRIBUTE_NAME = "name";
	public static final String PROPERTY_ATTRIBUTE_VALUE = "value";
	
	public static final String PROPERTY_ACTION_SUCCESS = "##SUCCESS##";
	public static final String PROPERTY_ACTION_FAIL = "##FAILED##";
	public static final String PROPERTY_TOKEN_GROUP = "##GROUP##";
	public static final String PROPERTY_TOKEN_NAME = "##NAME##";
	public static final String PROPERTY_TOKEN_VALUE = "##VALUE##";
	public static final String PROPERTY_TOKEN_ROW = "##ROW##";
	
	public PropertyManager() {
		nameValueDao = new NameValueDAO();
	}
	
	public String findPropertyGroup(String group) {
		return propertyMessageBuilder(nameValueDao.findByGroup(group));
	}
	
	public String findProperty(String group, String name) {
		return propertyMessageBuilder(nameValueDao.findByGroupName(group, name));
	}
	
	public String saveProperty(String group, String name, String value) {
		String result = PROPERTY_ACTION_SUCCESS;
		try {
			NameValueVO vo;
			List<NameValueVO> nameValueVOList = nameValueDao.findByGroupName(group, name);
			if(nameValueVOList.size() > 0) {
				vo = nameValueVOList.get(0);
			} else {
				vo = NameValueVO.createDefaultInstance();
				vo.setKeyGroup(group);
				vo.setKeyName(name);
				vo.setKeyValue(value);
			}
			
			nameValueDao.save(vo);
		} catch (Throwable t) {
			result = PROPERTY_ACTION_FAIL;
		}
		
		return result;
	}
	
	public String deleteProperty(String group, String name) {
		String result = PROPERTY_ACTION_SUCCESS;
		try {
			List<NameValueVO> vo = nameValueDao.findByGroupName(group, name);
			nameValueDao.delete(vo);
		} catch (Throwable t) {
			result = PROPERTY_ACTION_FAIL;
		}
		
		return result;
	}
	
	private String propertyMessageBuilder(List<NameValueVO> voList) {
		StringBuilder sb = new StringBuilder();
		
		for(NameValueVO vo : voList) {
			sb.append(PROPERTY_TOKEN_ROW);
			sb.append(PROPERTY_TOKEN_GROUP);
			sb.append(vo.getKeyGroup());
			sb.append(PROPERTY_TOKEN_NAME);
			sb.append(vo.getKeyName());
			sb.append(PROPERTY_TOKEN_VALUE);
			sb.append(vo.getKeyValue());
		}
		
		return sb.toString();
	}
}
